//导入
const express = require('express');
const bodyparser = require('body-parser');
const cookieParser = require('cookie-parser');
const config = require('./config');
const jwt = require('express-jwt');

const interfaces_user = require('./interfaces/user');
const interfaces_footprint = require('./interfaces/footprint');
const interfaces_footprintsrc = require('./interfaces/footprintsrc');
const interfaces_friend = require('./interfaces/friend');
const interfaces_article = require('./interfaces/article');
const interfaces_backstage = require('./interfaces/backstage');
//数据库
const mysql = require('mysql')
const connection = mysql.createPool(config.database);
const app = express();
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(cookieParser());


let query = function (sql, params, callback) {
  connection.getConnection(function (err, conn) {
    if (err) {
      console.log("getConnection")
      callback(err, null, null);
    } else {
      conn.query(sql, params, function (err, val, fields) {
        //事件驱动回调
        callback(err, val, fields);
        //释放连接
        conn.release();
      });
    }
  });
};


app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "x-requested-with, Content-Type,Authorization");
  res.header("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE");
  /*
   res.header("Content-Type", "application/json;charset=utf-8");
   res.header("Access-Control-Allow-Credentials:true");
   */
  next();
});

//注册接口

interfaces_user(app, query, jwt);
interfaces_footprint(app, query, jwt);
interfaces_footprintsrc(app, query, jwt);

interfaces_friend(app, query, jwt);
interfaces_article(app, query, jwt);
interfaces_backstage(app, query, jwt);

let server = app.listen(config.port, function () {
  const host = server.address().address;
  const port = server.address().port;
  console.log("server open", host, port);
  //res.send('hello world'); 发送信息
});

